package com.gbb.common.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;

import com.gbb.common.AppUtils;

import java.util.Map;

/**
 * SharedPreferences工具类
 *
 * @author gaobingbing
 */
public class PreferencesUtil {

    private SharedPreferences sp;

    private PreferencesUtil(String sharedName) {
        sp = AppUtils.get().getSharedPreferences(sharedName,Context.MODE_PRIVATE);
    }

    public static PreferencesUtil get(String sharedName) {
        return new PreferencesUtil(sharedName);
    }

    /**
     * @param key Key值
     * @param value String、Boolean、Integer、Long、Float
     */
    public void putObject(String key,Object value) {
        SharedPreferences.Editor editor = sp.edit();
        if(value instanceof String) {
            editor.putString(key,(String)value);
        } else if(value instanceof Boolean) {
            editor.putBoolean(key,(Boolean)value);
        } else if(value instanceof Integer) {
            editor.putInt(key,(Integer)value);
        } else if(value instanceof Long) {
            editor.putLong(key,(Long)value);
        } else if(value instanceof Float) {
            editor.putFloat(key,(Float)value);
        }
        editor.apply();
    }

    public String getString(String key,String defaultVal) {
        return sp.getString(key,defaultVal);
    }

    public boolean getBoolean(String key,boolean defaultVale) {
        return sp.getBoolean(key,defaultVale);
    }

    public int getInt(String key,int defaultValue) {
        return sp.getInt(key,defaultValue);
    }

    public long getLong(String key,int defaultValue) {
        return sp.getLong(key,defaultValue);
    }

    public float getFloat(String key,float defaultValue) {
        return sp.getFloat(key,defaultValue);
    }

    public Map<String, ?> getAll() {
        return sp.getAll();
    }

    /**
     * 清除Share文件
     */
    public void clearShareFile() {
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        editor.apply();
    }

    public void registerChangeListener(OnSharedPreferenceChangeListener listener) {
        sp.registerOnSharedPreferenceChangeListener(listener);
    }

}
